package com.cg.big_event.controller;
import com.cg.big_event.entity.Result;
import com.cg.big_event.entity.User;
import com.cg.big_event.service.UserService;
import com.cg.big_event.utils.JwtUtil;
import com.cg.big_event.utils.Md5Util;
import com.cg.big_event.utils.ThreadLocalUtil;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Validated
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,  @Pattern(regexp = "^\\S{5,16}$") String password){
        //查询用户
       User u= userService.findUserByName(username);
           //判断用户名是否被占用
           if(u==null)
           {
               //注册
               userService.register(username,password);
               //返回成功
               return Result.success();
           }
           else
           {
               return Result.error("用户名已存在");
           }
       }
       @PostMapping("/login")
    public Result login(String username,String password)
       {
           //查询用户
         User user = userService.findUserByName(username);
         if(user==null)
         {
             return Result.error("用户名不存在");
         }
         //验证密码
         if(Md5Util.getMD5String(password).equals(user.getPassword()))
         {
            //生成token
             Map<String, Object> claims = new HashMap<>();
             //添加用户信息
             claims.put("id",user.getId());
             //添加用户名
             claims.put("username",user.getUsername());
             //生成token
             String token = JwtUtil.genToken(claims);
             //在将生成的token放入ThreadLocal中时我们需要将其存入REDIS中,设置过期时间
             ValueOperations<String, String> Operations = redisTemplate.opsForValue ();
             Operations.set (token,token,1, TimeUnit.HOURS);
             //返回token
             return Result.success(token);
         }
         return Result.error("密码错误");
       }
       //根据用户名获取用户详细信息
       @GetMapping("/userInfo")
    public Result info()
       {
           //从ThreadLocal中获取用户信息
           Map<String,Object> map= ThreadLocalUtil.get();
           //查询用户,从token中获取用户名
           String username = (String) map.get("username");
           //查询用户
           User user = userService.findUserByName(username);
           //返回用户信息
           return Result.success(user);
       }
       @PutMapping("/update")
       //@RequestBody将json数据转换为对象
    public Result update(@RequestBody @Validated User user)
       {
           //更新用户信息
           userService.update(user);
           //返回成功
           return Result.success();
       }
       //更新头像
   @PatchMapping("/updateAvater")
    public Result updateAvater(@RequestParam @URL String avatarUrl){
        userService.updateAvater(avatarUrl);
        return Result.success();
   }
   @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params,@RequestHeader("Authorization") String token){
      //
       String oldPwd = params.get( "old_pwd" );
       String newPwd = params.get("new_pwd");
       String rePwd= params.get("re_pwd");
       //判断参数是否为空
      if ( !StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
          return Result.error ( "参数不能为空" );
        }
      //验证密码
      Map<String,Object> map = ThreadLocalUtil.get ();
       //获取用户名
       String s= (String)map.get ("username");
       //查询用户拿到原密码
       User loginuser =userService.findUserByName(s);
       //判断原密码是否正确
       if(!loginuser.getPassword ().equals ( Md5Util.getMD5String (oldPwd)))
       {
           return Result.error ( "原密码不正确!" );
       }//判断两次密码是否一致
       if(!newPwd.equals (rePwd))
       {
           return Result.error ( "两次密码不一致" );
       }
       userService.updatePwd(newPwd);
       //密码更新成功后删除原来的token
       ValueOperations<String, String> stringStringValueOperations = redisTemplate.opsForValue ();
       //删除token 并返回成功
       stringStringValueOperations.getOperations ().delete (token);
       return Result.success ();
   }
}
